<template>
  <scroll-view
    class="h-screen"
    scroll-y
    :refresher-triggered="refreshing"
    refresher-enabled
    @refresherrefresh="onRefresh"
    @scrolltolower="onReachBottom"
  >
    <UniAdminPanel
      ref="panelRef"
      :fetcher="fetcher"
      @add="onAdd"
      @edit="onEdit"
      @delete="onDelete"
      @query="onQuery"
    >
      <!-- 筛选插槽 -->
      <template #filters>
        <view class="flex items-center gap-2">
          <wd-input
            v-model="filters.nickname"
            placeholder="请输入用户姓名"
            clearable
            class="flex-1"
          />
          <wd-button type="success" size="small" @click="applyFilters">
            搜索
          </wd-button>
          <wd-button size="small" plain @click="resetFilters">重置</wd-button>
        </view>
      </template>

      <!-- 列表项插槽 -->
      <template #item="{ row }">
        <view
          class="p-3 rounded-xl bg-white shadow-sm flex justify-between items-center"
        >
          <view class="flex items-center gap-3">
            <image
              v-if="row.head"
              :src="row.head"
              class="w-[80rpx] h-[80rpx] rounded-full"
              mode="aspectFill"
            />
            <view class="flex flex-col">
              <view class="font-medium text-base">{{ row.name }}</view>
              <view class="text-sm text-gray-500 mt-1"
                >昵称: {{ row.nickname }}</view
              >
              <view class="text-sm text-gray-500 mt-1"
                >年龄: {{ row.age }} ｜ 性别:
                {{
                  row.gender === 'male'
                    ? '男'
                    : row.gender === 'female'
                      ? '女'
                      : '未知'
                }}</view
              >
            </view>
          </view>
          <view class="flex gap-2 ml-3">
            <wd-button size="small" type="success" plain @click="onEdit(row)">
              编辑
            </wd-button>
            <wd-button size="small" type="error" plain @click="onDelete(row)">
              删除
            </wd-button>
          </view>
        </view>
      </template>
    </UniAdminPanel>
  </scroll-view>

  <!-- 表单弹层：添加/编辑用户 -->
  <wd-overlay v-model:show="showForm" position="center" :maskClosable="false">
    <view class="wrapper">
      <view class="w-[85%] bg-white rounded-xl flex flex-col px-4 py-6">
        <view class="text-lg font-bold mb-4 text-center">{{ formTitle }}</view>

        <wd-form ref="formRef" :model="formModel">
          <wd-cell-group border>
            <wd-input
              label="用户名"
              label-width="100px"
              prop="name"
              clearable
              v-model="formModel.name"
              placeholder="请输入用户名"
              :rules="[{ required: true, message: '请填写用户名' }]"
            />
            <wd-input
              label="昵称"
              label-width="100px"
              prop="nickname"
              clearable
              v-model="formModel.nickname"
              placeholder="请输入昵称"
              :rules="[{ required: true, message: '请填写昵称' }]"
            />
            <wd-input
              label="密码"
              label-width="100px"
              prop="password"
              type="password"
              v-model="formModel.password"
              placeholder="请输入密码（编辑时不回显）"
              :rules="[{ required: formModel.id === 0, message: '请填写密码' }]"
            />
          </wd-cell-group>

          <view class="flex justify-end gap-2 mt-4">
            <wd-button size="small" plain @click="showForm = false"
              >取消</wd-button
            >
            <wd-button type="primary" size="small" @click="handleSubmit"
              >保存</wd-button
            >
          </view>
        </wd-form>
      </view>
    </view>
  </wd-overlay>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { useToast } from 'wot-design-uni'
import UniAdminPanel from '@/components/Table/tableComponet.vue'
import { userList, updateUser, deleteUser } from '@/api/user'

const { success: showSuccess } = useToast()
const panelRef = ref<any>(null)
const refreshing = ref(false)

const filters = reactive({ nickname: '' })

const showForm = ref(false)
const formTitle = ref('新增用户')

const formModel = reactive({
  id: 0,
  name: '',
  nickname: '',
  password: ''
})

const formRef = ref<any>(null)

const fetcher = async ({ page = 1, size = 10 }: any) => {
  const res = await userList<
    { page: number; pageSize: number; nickname?: string },
    IUser
  >({
    page,
    pageSize: size,
    nickname: filters.nickname
  })
  console.log(res)

  const { items, total } = res.data
  console.log(items, total)
  return {
    items,
    hasMore: page * size < total
  }
}

// 下拉刷新 / 底部加载
const onRefresh = async () => {
  refreshing.value = true
  await panelRef.value?.refresh()
  refreshing.value = false
}
const onReachBottom = () => panelRef.value?.loadMore()

// 搜索 / 重置
const applyFilters = () => panelRef.value?.refresh()
const resetFilters = () => {
  filters.nickname = ''
  panelRef.value?.refresh()
}

// 新增
const onAdd = () => {
  uni.showToast({ title: '用户不允许新增', icon: 'none' })
}

// 编辑
const onEdit = (row: IUser) => {
  formTitle.value = '编辑用户'
  Object.assign(formModel, {
    id: row.id,
    name: row.name,
    nickname: row.nickname,
    password: '' // 不回显
  })
  showForm.value = true
}

// 删除
const onDelete = (row: IUser) => {
  uni.showModal({
    title: '删除用户',
    content: `确定删除 "${row.name}" 吗？`,
    success: async (res: any) => {
      if (res.confirm) {
        await deleteUser<{ id: number }, any>({ id: row.id })
        uni.showToast({ title: '已删除', icon: 'none' })
        panelRef.value?.refresh()
      }
    }
  })
}

// 查询事件（面板自带）
const onQuery = (f: any) => {
  console.log('查询条件:', f)
}

// 提交表单
async function handleSubmit() {
  const result = await formRef.value.validate()
  if (result.valid) {
    await updateUser<typeof formModel, any>({ ...formModel })
    showSuccess({ msg: formModel.id === 0 ? '新增成功' : '修改成功' })
    showForm.value = false
    panelRef.value?.refresh()
  }
}
</script>

<style scoped lang="scss">
.wrapper {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
</style>
